<template>
  <div class="translate">
    <Textarea v-model="originValue" width="45%" height="90%" :clearable="true"></Textarea>
    <Button class="translate-button" @click="translate">翻译</Button>
    <Textarea v-model="translateValue" width="45%" height="90%" v-loading="loading">
      <div class="translate-header">
        <i class="iconfont iconfuzhi" @click="copyResult"></i>
      </div>
    </Textarea>
  </div>
</template>

<script setup lang="ts">
import message from '@/components/msg/msg'
import Textarea from '@/components/Textarea/index.vue'
import Button from '@/components/button.vue'
import axios from 'axios'
import { ref } from 'vue'
import md5encryption from 'js-md5'
import { copy } from '@/util/util'

const originValue = ref<string>('')
const translateValue = ref<string>('')
const loading = ref<boolean>(false)

// 发起翻译请求
const translateReq = async (originData: string) => {
  try {
    loading.value = true
    const appid = '20240418002027961' // appid
    const salt = Math.random() // 盐
    const code = 'DdG0pGLeo3Vk0RZOoqXQ' // 密钥
    const sign = `${appid}${originData}${salt}${code}`
    const md5Sign = md5encryption(sign)
    const { data, statusText } = await axios.get('/api1', {
      params: {
        from: 'auto',
        to: 'auto',
        q: originData,
        salt,
        sign: md5Sign,
        appid
      }
    })
    const [trans_result] = data?.trans_result || []
    translateValue.value = trans_result?.dst || ''
  } catch (e) {
    message.error('翻译调用失败')
  } finally {
    loading.value = false
  }
}

// 复制翻译结果
const copyResult = () => {
  copy(translateValue.value)
}

const translate = () => {
  const textareaValue = originValue.value
  if (textareaValue.trim()) {
    translateReq(textareaValue.trim())
  }
}
</script>

<style lang="scss" scoped>
@import './style.scss';
</style>
